package connect

import (
	"fmt"
	"sync/atomic"
)

type Room struct {
	roomId      int
	roomName    string
	onlineCount int64
	userGroup   *UserGroup
}

func NewRoom() *Room {
	return &Room{
		roomId:      1,
		userGroup:   NewUserGroup(),
		onlineCount: 0,
	}
}

func (room *Room) AddUser(user *User) {
	room.userGroup.Add(user)
	atomic.AddInt64(&room.onlineCount, 1)
	room.broadcast(NewMessageSystem(room.roomId, "group", fmt.Sprintf("用户 %s 加入房间，当前房间 %d 人", user.UserName, room.onlineCount)), user.UserId)
}

func (room *Room) DelUser(user *User) {
	if room.userGroup.Del(user.UserId) {
		atomic.AddInt64(&room.onlineCount, -1)
		room.broadcast(NewMessageSystem(room.roomId, "group", fmt.Sprintf("用户 %s 退出房间，当前房间 %d 人", user.UserName, room.onlineCount)), user.UserId)
	}
}

func (room *Room) Push(user *User, msg Message) {
	room.broadcast(msg, user.UserId)
}

func (room *Room) broadcast(message Message, except string) {
	room.userGroup.ForEach(func(user *User) {
		if user.UserId != except {
			user.Push(message.GetData())
		}
	})
}
